<?php
// 本类由系统自动生成，仅供测试用途
namespace Admin\Controller;
use Think\Controller;
class ChannelCodeController extends Controller {
    public  function getCodeChennle(){
      $this->Islogin();
      $userid  = session('lampzuo_id');
      $wayusercode = M('wayuser_code');
      $wayusercode = M('wayuser');
      $admin       = M('admin');
      $user   = $admin->where(array('id'=>$userid))->find();
      $way    = $wayusercode->where(array('admin_id'=>$userid))->select();
      $arr = array();
      for ($i=1; $i < $user['chennl_code']; $i++) { 
          array_push($arr,$i);
      }
      foreach ($way as $key => $value) {
          foreach($arr as $k=>$v) {
            if($v == $value['code_number']){
                unset($arr[$k]);
            }
          }
      }
      $this->ajaxReturn($arr,'json');
    }
    /**
     * 渠道生成二维码
     */
    public function index() {
        $this->Islogin();
        $admin  = M('admin');
        $userid = session('lampzuo_id');
        $datetime = date('Y-m-d');
        $path   = './Public/Uploads/DownloadCode/'.$userid.'/';
        $weburl = C('WEBURL');
        $user   = $admin->where(array('id'=>$userid))->find();
        if(!$user['chennl_code']){
           $user['chennl_code'] = 1; 
        }
        if(!is_dir($path)){
            mkdir($path,0777,true);
        }
        $x = 1;
        set_time_limit(0);
        $file=scandir($path);
        // $chennlnum = $user['chennl_code']+$x;
        // $usernum   = $user['usernum'].'0'.$chennlnum;
        // $chennode  = $chennlnum.'.png';
        // $qrres = $this->ceshiscerweima($weburl.'PIGjdc/login_first_step.html?pid='.$userid.'&code='.$chennlnum,$path.$chennode,$usernum,$chennlnum);
        for ($x=0; $x<=100; $x++) {
               $chennlnum = $user['chennl_code']+$x;
               $usernum   = $user['usernum'].'0'.$chennlnum;
               $chennode  = $chennlnum.'.png';
               $qrres = $this->ceshiscerweima($weburl.'PIGjdc/login_first_step.html?pid='.$userid.'&code='.$chennlnum,$path.$chennode,$usernum,$chennlnum);
               // $qrres = scerweima($weburl.'PIGjdc/login_first_step.html?pid='.$channel_data['admin_id'].'&code=0'.'&waynum='.$channel_data['waynum'],$path.$filename,$me_user_data['usernum']);
               // echo "数字是：$chennlnum <br>";
               if($x == 100){
                 $user   = $admin->where(array('id'=>$userid))->save(['chennl_code'=>$chennlnum]);
                  $this->ajaxReturn(['success'=>"OK"]);
               }
        }
    }

    /**
     * 生成原始的二维码(生成图片文件)  
     */
    function ceshiscerweima($url='',$path=false,$name,$chennlnum){
        // 二维码内容
        $value = $url;
        // 容错级别
        $errorCorrectionLevel = 'L';
        // 生成图片大小
        $matrixPointSize = 12; 
        if($path){
            $filename = $path;
        }else{
            $filename = false;
        }
        try{
            // 生成二维码图片
            \Org\Util\QRcode::png($value,$filename , $errorCorrectionLevel, $matrixPointSize, 1);
            // 准备好的logo图片
            $logo = C('PUBLIC_ROUTE').'/Public/mui/images/logo.png';
            // 准备好的背景图片
            // $back = C('PUBLIC_ROUTE').'/Public/mui/images/iconfont-tianjia.png';
            // $back = C('PUBLIC_ROUTE').'/Public/mui/images/logo2.png';
            if ($logo !== FALSE) {
              // $back_res = imagecreatefromjpeg($back);
              $back_res = imagecreatefrompng($back);
              $QR = imagecreatefrompng($filename);
              $logo = imagecreatefrompng($logo);
              // 背景图片宽度
              $back_width = imagesx($back_res);
              // 背景图片宽度
              $back_height = imagesy($back_res);
              // 二维码图片宽度
              $QR_width = imagesx($QR);
              // 二维码图片高度
              $QR_height = imagesy($QR);
              // logo图片宽度
              $logo_width = imagesx($logo);
              // logo图片高度
              $logo_height = imagesy($logo);
              // logo
              $logo_qr_width = $QR_width / 6.5;
              $scale = $logo_width/$logo_qr_width;
              $logo_qr_height = $logo_height/$scale;
              $from_width = ($QR_width - $logo_qr_width) / 2;
              // 背景图
              $qr_back_width = $QR_width / 8.5;
              $scale_back = $back_width/$qr_back_width;
              $qr_back_height = $back_height/$scale_back;
              $from_back_width = ($QR_width - $qr_back_width) / 2;
              // 重新组合图片并调整大小 
              imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width, $logo_qr_height, $logo_width, $logo_height);
            }
            // 保存二维码图片
            imagejpeg($QR,$filename,100);
            
            // 重新组合图片并调整大小
            imagecopyresampled($QR, $back_res, $from_back_width, $from_back_width, 0, 0, $qr_back_width, $qr_back_height+10, $QR_width, $QR_height);
            // 保存图片
            imagejpeg($QR,$filename,100);
            if(file_exists($filename)){
                chmod($filename, 0777);
                $resimg = $this->makeImg($filename,$name,$chennlnum);
                return $filename;
            }else{
                return false;
            }
        } catch(\Think\Exception $e){
            return false;
        }
        return true;
    }

    public function makeImg($filename,$name,$chennlnum)
    {
        // header("Content-Type:text/html; charset=utf-8");
        // header('Content-type: image/png');// 告诉浏览器，这个文件，是一个png图片
        //字体大小
        $size = 8;
        //字体类型，本例为黑体
        $font = "./Public/Home/fonts/songti.ttf";
        //显示的文字
        $waterImageUrl = 12345678;
        //1、创建画布
        $img = imagecreatefromjpeg($filename);// 加载已有图像
        // 二维码图片宽度
        $QR_width = imagesx($img);
        $textcolor=imagecolorallocate($img,0,0,0);
        $daax = $name;
         if($chennlnum <= 10){
            imagettftext($img,$size,0,$QR_width/2.28,254,$textcolor,$font,$daax);
        }else{
            imagettftext($img,$size,0,$QR_width/2.35,254,$textcolor,$font,$daax);
        }
        
        
        // $daax = "左定强邀请您加入筋斗车";
        //2、写字
        // $str = iconv("UTF-8","GBK",$daax);
        // var_dump($daax,'..');die;
        //发送头信息
        // header('Content-Type: image/png');
        //输出图片
        // ImagePNG($img);
        //保存图片至指定路径
        ImagePNG($img, $filename);
        imagedestroy($img);
        return true;
    }

    public function getDownloadCode(){
      $this->Islogin();
      $coedarr = array();
      $userid = session('lampzuo_id');
      $wayusercode = M('wayuser_code');
      $way    = $wayusercode->where(array('aid'=>$userid))->select();
      $arr = array();
      foreach ($way as $key => $value) {
          array_push($arr,$value['code']);
      }
     
      $webbuel = C('WEBURL');
      $path = './Public/Uploads/DownloadCode/'.$userid;
      if(is_dir($path)){
        $mdir = opendir($path);
        while( ($filename = readdir($mdir)) !== false ) {
          if($filename != "." && $filename != ".."){
              $file = explode(".",$filename);
              $coedarr[$file[0]] = $filename;
          }
        }
        ksort($coedarr);
      }
      foreach ($coedarr as $key => $value) {
         foreach ($arr as $k) {
              if($k == $key){
                unset($coedarr[$key]);
              }
          }
      }
      $this->ajaxReturn(['data'=>$coedarr,'wedurl'=>$webbuel,'pid'=>$userid],'json');
    }
    
    /**
     * 下载二维码文件
     */
    public function DownloadScerweima() {
        $userid = session('lampzuo_id');
        $filename_str = I('get.filename');
        if(empty($filename_str)){
           return false;
        }
        $path = C('PUBLIC_ROUTE').'/Public/Uploads/DownloadCode/'.$userid.'/';
        $filename = $path.ltrim($filename_str,'/');
        header("Content-type: octet/stream");
        // 告诉浏览器通过附件形式来处理文件
        header( "Content-disposition:attachment;filename=".$filename_str); 
        // 下载文件大小
        header('Content-Length:'.filesize($filename)); 
        // 读取文件内容
        readfile($filename);
    }

  public  function insertSort($arr) {
    $len = count($arr);
    for ($i = 1; $i < $len; $i++) {
        if ($arr[$i] < $arr[$i - 1]) {
            $t = $arr[$i];
            $j = $i - 1;
            // 如果当前元素大于前一个元素，就往前挪
            while ($j >= 0 && $t < $arr[$j]) {
                $arr[$j + 1] = $arr[$j];
                $j--;
            }
            $arr[$j + 1] = $t;
        }
    }
    return $arr;
}
}